/**
 * Created by fangshufeng on 2017/11/20.
 */

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var dbConfig = require('./DB/DBConfig');
var business = require('./DB/Business');
var response = require('./ReposeData/Response');

var developSql = require('./DB/DevelopSql');

var busiRealtionship = require('./DB/BusiRelationshipSql');

let mock = require('./DB/Mock');
/**
 * 获取业务线列表
 * */
router.get('/businessList', function (req, res, next) {

    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (!err) {
            var selectSql = business.queryAll;
            connection.query(selectSql, function (err, resp) {
                if (err) {
                    response.msg = JSON.stringify(err.toString());
                    response.flag = '0';

                    res.send(response);
                } else {
                    // res.setHeader("Access-Control-Allow-Origin","*");
                    response.data = resp;
                    res.json(response);
                }
            });
        } else {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            res.send(response);
        }
        connection.end();
    });
});

/**
 * 获取业务线列表 并且对应的开发人员列表
 * data :{
 *  "nono":['A',B],
 *  'mxd':['C','D']
 * }
 * */
router.get('/businessListAndDev', function (req, res, next) {

    var connection = mysql.createConnection(dbConfig);

    connection.connect(function (err) {

        if (err) {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            responseAction(response)
            return;
        }

        /**
         * 查询业务线
         * */
        var selectSql = business.queryAll;
        connection.query(selectSql, function (err, resp) {
            if (err) {
                response.msg = JSON.stringify(err.toString());
                response.flag = '0';
                responseAction(response)
                return;
            }
            busiForsubDevs(resp);

        });

    });

    /**
     * 每个业务线下面的所有开发人员
     * [ { id: 1, business_name: 'nono' },{ id: 2, business_name: 'mxd' }]
     *
     * to
     * {
     *  'nono':[{id: 1, dev_id: 1,dev_name:'方树风',busi_id:1},{id: 2, dev_id: 2,dev_name:'方树风2',busi_id:2}],
     *  'mxd':[{id: 1, dev_id: 1,dev_name:'方树风',busi_id:1},{id: 2, dev_id: 2,dev_name:'方树风2',busi_id:2}]
     * }
     * */
    function busiForsubDevs(devs) {
        recursionBusiIds(devs, 0, {}, function (obj) {
            response.data = obj;
            responseAction(response);
        });

    };

    function recursionBusiIds(devs, index, originObj, action) {
        let fixObj = originObj;
        if (index === devs.length) {
            action(fixObj);
            return;
        }
        let busi_id = devs[index]['id'];
        let busi_name = devs[index]['business_name'];
        connection.query(busiRealtionship.searchDevsInBusiID, [busi_id], function (err, resp) {
            recursionDevs(resp, [], 0, function (fixResult) {
                fixObj[busi_name] = fixResult;
                index++;
                recursionBusiIds(devs, index, fixObj, action);
            });
        });
    };

    function recursionDevs(devs, fixResult, currentIndex, nextAction) {
        let tempResult = fixResult;
        if (currentIndex === devs.length) {
            nextAction(tempResult);
            return;
        }
        let tempObj = devs[currentIndex];
        let dev_id = tempObj['dev_id'];
        connection.query(developSql.searchItem, [dev_id], function (err, resp) {
            if (resp.length) {
                tempObj['dev_name'] = resp[0]['dev_name'];
            } else {
                tempObj['dev_name'] = '';
            }
            tempResult.push(tempObj);
            currentIndex++;
            recursionDevs(devs, tempResult, currentIndex, nextAction);
        });

    }

    function responseAction(response) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.send(response);
        connection.end();
    }
});

/**
 * 增加业务线 入参 businessName
 * */
router.post('/addBusiness', function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var businessName = req.body.businessName || '';
    if (businessName.length == 0) {
        response.flag = '0';
        response.msg = '参数不能为空';
        response.data = [];
        res.send(response);
        return;
    }

    var connection = mysql.createConnection(dbConfig);

    connection.connect(function (err) {
        if (err) {
            finishAction('0', '链接数据库失败' + JSON.stringify(err.toString()));
            return;
        }
        connection.query(business.queryAll, function (err, resps) {
            if (err) {
                finishAction('0', '查询数据失败' + JSON.stringify(err.toString()));
                return;
            }
            var isExit = false;
            for (var i = 0; i < resps.length; i++) {
                if (resps[i].business_name === businessName) {
                    isExit = true;
                    break;
                }
            }
            if (isExit) {
                finishAction('0', '业务线已存在');
                return;
            }
            connection.query(business.insert, [businessName], function (err, resp) {
                if (err) {
                    finishAction('0', '插入数据失败：' + JSON.stringify(err.toString()));
                    return;
                }
                finishAction('1', '插入成功!');
            });
        });
    });

    function finishAction(flag, msg) {
        response.msg = msg;
        response.flag = flag;
        res.send(response);
        connection.end();
    }
});


/**
 * 获取开发人员列表
 * */
router.get('/developList', function (req, res, next) {

    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (!err) {
            connection.query(developSql.queryAll, function (err, resp) {
                if (err) {
                    response.msg = JSON.stringify(err.toString());
                    response.flag = '0';
                    res.send(response);
                } else {
                    response.data = resp;
                    res.json(response);
                }
            });
        } else {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            res.send(response);
        }
        connection.end();
    });
});

/**
 * 增加开发人员
 * 入参
 * [业务线的名称]         businessName
 * [开发人员的名称]        developName
 * */
router.post('/addDevelop', function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var businessName = req.body.businessName;
    var developName = req.body.developName;
    if (businessName.length === 0 || developName === 0) {
        response.msg = '参数不能为空';
        response.flag = '0';
        res.send(response);
        return;
    }

    var connection = mysql.createConnection(dbConfig);

    function resposeFix(flag, msg, data) {
        response.msg = msg;
        response.flag = flag;
        response.data = data;
        res.send(response);
        connection.end();
    }

    function searchBusi_id(callBack) {
        connection.query(business.search, [businessName], function (err, resp) {
            if (err) {
                callBack(-1);
            }
            callBack(resp[0].id);
        });
    }

    /**
     * 插入developer表
     **/
    function insertDevelop() {
        searchBusi_id(function (bus_id) {
            if (bus_id === -1) {
                resposeFix('0', '获取业务线id失败', []);
                return;
            }
            connection.query(developSql.insert, [developName], function (err, resp) {
                if (err) {
                    resposeFix('0', '插入失败', [], res);
                    return;
                }
                var insertId = resp.insertId;
                insertRelationship(insertId, bus_id, function (result) {
                    if (result) {
                        resposeFix('1', '插入成功', [], res);
                    } else {
                        resposeFix('0', '插入失败', [], res);
                    }
                });
            });
        });

    }

    /**
     * 插入busi_dev_relationship表
     **/
    function insertRelationship(dev_id, buni_id, callback) {
        connection.query(busiRealtionship.insert, [dev_id, buni_id], function (err, resp) {
            if (err) {
                callback(false);

            }
            callback(true);
        });
    }

    /**
     * 链接数据库
     **/
    connection.connect(function (err) {
        if (err) {
            resposeFix('0', '数据库链接失败', [], connection);
            return;
        }

        /**
         * 1) businessName表是否已经存在当前业务线
         **/
        var busi_id = -1;
        connection.query(business.search, [businessName], function (err, respsB) {

            if (err) {
                resposeFix('0', 'business表查询失败' + JSON.stringify(err.toString()), []);
                return;
            }

            if (respsB.length === 0) {
                resposeFix('0', '没有该分类' + JSON.stringify(err.toString()), []);
                return;
            }

            busi_id = respsB[0].id;

            /**
             * 2) developer表是否已经存在当前开发者
             **/
            var dev_id = -1;

            connection.query(developSql.search, [developName], function (err, resps) {
                if (err) {
                    resposeFix('0', 'developer表查询失败' + JSON.stringify(err.toString()), []);
                    return;
                }

                if (resps.length === 0) {
                    insertDevelop();
                    return;
                }

                dev_id = resps[0].id;

                /**
                 * 3) 查询busi_dev_relationship表是否已经存在该元素
                 **/
                connection.query(busiRealtionship.search, [dev_id, busi_id], function (err, resp) {
                    if (err) {
                        resposeFix('0', 'busi_dev_relationship表查询失败' + JSON.stringify(err.toString()), []);
                        return;
                    }
                    if (resp.length > 0) {
                        resposeFix('0', '该开发人员类型已经存在', []);
                        return;
                    }
                    insertDevelop();
                });
            });
        });
    });

});


/***
 * **************** **************** **************** MockData表操作 **************** **************** **************** ***************
 * */

/**
 * 获取mock数据
 * 参数relation_id
 * */
router.get('/mockData', function (req, res, next) {

    let relation_id = req.query.relation_id || '';

    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (!err) {
            connection.query(mock.search, [relation_id], function (err, resp) {
                if (err) {
                    response.msg = JSON.stringify(err.toString());
                    response.flag = '0';
                    res.send(response);
                } else {
                    response.data = resp;
                    res.setHeader("Access-Control-Allow-Origin", "*");
                    res.json(response);
                }
            });
        } else {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            res.send(response);
        }
        connection.end();
    });
});

/**
 * 更新mock数据
 * 参数
 *      mock_id
 *      data  返回数据
 *      name  接口名称
 *      path 接口路径
 * */
router.post('/updateMockData', function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var mock_id = req.body.mock_id;
    var data = req.body.data;
    var name = req.body.name;
    var path = req.body.path;
    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (err) {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            res.send(response);
            connection.end();
            return;

        }

        connection.query(mock.update, [name, path, data, mock_id], function (err, resp) {
            if (err) {
                response.msg = JSON.stringify(err.toString());
                response.flag = '0';
                res.send(response);
                connection.end();
                return;
            }
            response.data = resp;
            res.json(response);
            connection.end();
        });

    });
});

/**
 * 删除mock数据
 * 参数
 *      mock_id
 * */
router.post('/deleteMockData', function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var mock_id = req.body.mock_id;
    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (err) {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            res.send(response);
            connection.end();
            return;

        }

        connection.query(mock.delete, [mock_id], function (err, resp) {
            if (err) {
                response.msg = JSON.stringify(err.toString());
                response.flag = '0';
                res.send(response);
                connection.end();
                return;
            }

            response.data = resp;
            res.json(response);
            connection.end();
        });

    });
});


/**
 * 增加mock数据
 * 参数
 *      mock_id
 *      data  返回数据
 *      name  接口名称
 *      path 接口路径
 * */
router.post('/addMockData', function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    var mock_id = req.body.mock_id;
    var data = req.body.data;
    var name = req.body.name;
    var path = req.body.path;
    if (mock_id.length === '' ||
        data.length === '' ||
        name.length === '' ||
        path.length === ''
    ) {
        response.msg = '参数不合法';
        response.flag = '0';
        res.send(response);
        return;
    }
    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (err) {
            response.msg = JSON.stringify(err.toString());
            response.flag = '0';
            res.send(response);
            connection.end();
            return;

        }

        connection.query(mock.insert, [name, path, data, mock_id], function (err, resp) {
            if (err) {
                response.msg = JSON.stringify(err.toString());
                response.flag = '0';
                res.send(response);
                connection.end();
                return;
            }

            response.data = resp;
            res.json(response);
            connection.end();
        });

    });
});


/***
 * **************** **************** **************** 对外操作 **************** **************** **************** ***************
 * */

function fetchMockDataAction(id, path, res) {

    var connection = mysql.createConnection(dbConfig);
    connection.connect(function (err) {
        if (err) {
            res.send({
                'errorCode': '0000001',
                'data': null,
                'succeed': false,
                'errorMessage': JSON.stringify(err.toString())
            });
            connection.end();
            return;
        }

        connection.query(mock.searchOnlyData, [id, path], function (err, resp) {
            connection.end();
            if (err) {
                res.send({
                    'errorCode': '0000001',
                    'data': null,
                    'succeed': false,
                    'errorMessage': JSON.stringify(err.toString())
                });
                return;
            }
            if (resp.length === 0) {
                res.send({
                    'errorCode': '0000001',
                    'data': null,
                    'succeed': false,
                    'errorMessage': '数据为空'
                });
            } else {
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.json(JSON.parse(resp[0].data));
            }

        });
    });
}

router.get('/fetchMockData/:id/:path', function (req, res, next) {
    let id = req.params.id || '';
    let path = req.params.path || '';
    fetchMockDataAction(id, path, res);

});

router.post('/fetchMockData/:id/:path', function (req, res, next) {
    let id = req.params.id || '';
    let path = req.params.path || '';
    console.log(id,path)
    fetchMockDataAction(id, path, res);
});

module.exports = router;

